WEBAPP['pageVtubeHome'] = function() {
	$.each(CLIP.init, function(key, func) {
		func();
	});
};

var CLIP = {
	playerChoice : 0,
	go : function(path) {
		path = '#!' + path;
		if (location.hash == path) {
			$(window).hashchange();
		} else {
			document.location.hash = path;
		}
	}
};

CLIP.init = {
	search : function() {
		$('#searchForm').submit(function() {
			var path = 'Search?' + $.trim($('#keyword').val());
			CLIP.go(path);

			// clear
			path = null;

			return false;
		}).find('.del-button').on('click touch', function() {
			$(this).parent().next().val('');
		}).end();
	},

	filters : function() {
		$('#filterForm').find('input:radio').on('change', function() {
			var T = $(this);
			T.closest('.btn-group').find('.label-text').text(T.next().text());

			var path = 'Filters?' + $('#sorts input:checked').val() + '|' + $('#cats input:checked').val();

			CLIP.go(path);

			// clear
			T = null;
		});
	},

	hash : function() {
		$(window).hashchange(function(e) {
			var hash = location.hash.replace(/^#!/, "");
			var parts = hash.split('?', 2);
			if (CLIP[parts[0]] != undefined) {
				CLIP[parts[0]].go(parts[1]);
			}
		});

		if (location.hash) {
			$(window).hashchange();
		} else {
			$('#filterForm').find('input:radio:checked:first').trigger('change');
		}
	},

	more : function() {
		$('#clips').on('click touch', 'a.clip', function() {
			CLIP.Info.load($(this).attr('code'));
			return false;
		});

		$('#clipsMore').on('click touch', function() {
			CLIP.Clips.currentPage++;
			$('#page').val(CLIP.Clips.currentPage);
			CLIP.Clips.more(this);
		});

		$(window).scroll(function(e) {
			if ($('#tabClips').is(':visible')) {
				if ($(window).scrollTop() + 300 * bum.pixelRatio >= $(document).height() - $(window).height()) {
					$('#clipsMore:visible').click()
					// click xong hide liền để tránh trigger liên tục
					.hide();
				}
			}
		});
	},
};

CLIP.Search = {
	go : function(key) {
		$('#keyword').val(key);
		CLIP.Clips.resetPage();
		CLIP.Clips.more();
	}
};

CLIP.Filters = {
	go : function(data) {
		$('#keyword').val('');

		var parts = data.split('|', 2);
		$('#sorts').find('input[value="' + parts[0] + '"]').prop('checked', 'checked');
		$('#cats').find('input[value="' + parts[1] + '"]').prop('checked', 'checked');

		CLIP.Clips.resetPage();
		CLIP.Clips.more();
	}
};

CLIP.Clips = {
	currentPage : 1,
	resetPage : function() {
		CLIP.Clips.currentPage = 1;
	},

	more : function(item) {
		var keyword = $('#keyword').val();
		var url = null;
		if (keyword) {
			// search
			url = 'http://vntube.tv/page/' + CLIP.Clips.currentPage + '?s=' + keyword;
		} else {
			// list bình thường
			var cat = $('#cats input:checked').val();
			if (cat) {
				cat += '/';
			}
			url = 'http://vntube.tv/' + cat + 'page/' + CLIP.Clips.currentPage + '?orderby=' + $('#sorts input:checked').val();
		}

		// url = 'http://api.ola.vn/html/zmp3/load?url=' + url;
		bum.api.fetchUrl(url, CLIP.Chap.headers, CLIP.Clips.getMore);

		if (CLIP.Clips.currentPage === 0) {
			$('#clips').empty();
		}
		$('#tabClipsButton').tab('show');

		// clear
		url = keyword = null;
	},

	getMore : function(text) {
		text = bum.util.parse(text, '<!-- end .loop-actions -->', '<!-- end .loop-content -->');
		if (text == null) {
			OLAPI.callNative("showToast", 'Nội dung không tìm thấy hoặc đã hết...');
			return;
		}
		var html = [], count = 0;
		$.each(text.replace('\\"', '"').split('<div id='), function(i, clip) {
			if (i > 0) {
				++count;
				var code = bum.util.parse(clip, 'data-id="', '"');
				var title = bum.util.parse(clip, 'title="', '"');
				var originalTitle = bum.util.parse(clip, '<p class="entry-summary">', '</p>');
				var img = bum.util.parse(clip, '<img src="', '"');

				html.push('<a class="item clip" href="#" code="', code, '"><div class="cw">');
				html.push('<img src="', img, '"/>');
				html.push('<div class="iw"><h4>', title, '</h4>');
				html.push('<h5>', originalTitle, '</h5></div>');
				html.push('</div></a>');
			}
		});

		if (html.length == 0) {
			OLAPI.callNative("showToast", 'Nội dung không tìm thấy hoặc đã hết...');
			return;
		}

		html = html.join('');

		// trang đầu thì đè, trang next thì append
		if (CLIP.Clips.currentPage === 1) {
			$('#clips').html(html);
		} else {
			$('#clips').append(html);
		}

		// ẩn hiện nút load more
		if (count >= 8) {
			$('#clipsMore').show();
		} else {
			$('#clipsMore').hide();
		}

		// clear
		html = null;

	}
};

CLIP.Info = {
	code : null,

	genInfoCacheKey : function(code) {
		return 'vtube.info.' + code;
	},

	load : function(code) {
		CLIP.Info.code = code;
		var url = 'http://vntube.tv/wp-content/themes/detube/ajax.php?action=ajax-video&id=' + code;
		// url = 'http://api.ola.vn/html/zmp3/load?url=' + url;
		bum.api.fetchUrl(url, CLIP.Chap.headers, CLIP.Info.getInfo);

		// clear
		url = null;
	},

	getInfo : function(text) {
		var youtube = bum.util.parse(text, 'http://www.youtube.com/embed/', '?');
		// API_UTILS.saveCache('vtube', CLIP.Info.genInfoCacheKey(CLIP.Info.code), youtube);

		CLIP.Info.renderInfo(youtube);
		// clear
		youtube = null;
	},

	renderInfo : function(youtube) {
		var url = 'http://youtu.be/' + youtube;
		CLIP.Chap.playStream(url);
		// clear
		url = null;
	}
};

CLIP.Chap = {
	headers : [ 'Accept', 'text/plain, text/html', 'Host', 'vntube.tv', 'Cache-Control', 'max-age=0', 'Connection', 'close', 'User-Agent',
			'Mozilla/5.0 (Linux; U; Android 2.2; en-us; DROID2 GLOBAL Build/S273) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1' ].join('|'),

	playStream : function(url) {
		bum.api.playVideoUrl(url);
	}
};